package logic

import (
	"context"
	"strings"

	"mall/common/modelx"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendMemberListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendMemberListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendMemberListLogic {
	return &BackendMemberListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendMemberListLogic) BackendMemberList(in *user.BackendMemberListReq) (*user.BackendMemberListResp, error) {
	var orderBys []string
	if len(in.OrderBy) > 0 {
		for _, orderBy := range in.OrderBy {
			var order string = " ASC"
			if orderBy.Order == "1" {
				order = " DESC"
			}
			if orderBy.Field == "id" {
				orderBys = append(orderBys, model.UserColumns.ID+order)
			}
		}
	}
	var stati string
	if len(in.FilterBy) > 0 {
		for _, filterBy := range in.FilterBy {
			switch filterBy.Field {
			case "status":
				stati = filterBy.In
			}
		}
	}

	filterMap := make(map[string]map[string][]any)
	if in.MemberIds != "" {
		filterMap[model.UserColumns.ID] = map[string][]any{
			"in": modelx.UniqueValues(strings.Split(in.MemberIds, ","), 64),
		}
	}
	statusEqualTo := make([]any, 0, 1)
	if in.Status > 0 {
		statusEqualTo = append(statusEqualTo, in.Status)
	}
	statusIn := modelx.UniqueValues(strings.Split(stati, ","), 32)
	filterMap[model.UserColumns.UserStatus] = map[string][]any{
		"equalTo": statusEqualTo,
		"in":      statusIn,
	}

	if in.Account != "" {
		filterMap[model.UserColumns.UserLogin] = map[string][]any{
			"equalTo": []any{in.Account},
		}
	}
	if in.Email != "" {
		filterMap[model.UserColumns.UserEmail] = map[string][]any{
			"equalTo": []any{in.Email},
		}
	}
	if in.Mobile != "" {
		filterMap[model.UserColumns.UserMobile] = map[string][]any{
			"equalTo": []any{in.Mobile},
		}
	}

	userList, count, err := l.svcCtx.User.GetList(l.ctx, model.M{
		"page":     in.Current,
		"pageSize": in.PageSize,
		"search":   in.Search,
		"orderBy":  strings.Join(orderBys, ","),
	}, 1, filterMap)
	if err != nil {
		return nil, err
	}

	var members []*user.BackendMemberDetailResp
	if len(userList) > 0 {
		var uids []any // []model.User.ID
		for _, item := range userList {
			uids = append(uids, item.ID)
		}

		detailFilterMap := make(map[string]map[string][]any)
		detailFilterMap[model.UserDetailColumns.UserID] = map[string][]any{
			"in": uids,
		}
		detailList, _, err := l.svcCtx.User.GetDetailList(l.ctx, model.M{}, -1, detailFilterMap) // 读取关联表
		if err != nil {
			return nil, err
		}

		idDetailMap := make(map[uint64]*user.BackendMemberDetailResp)
		if len(detailList) > 0 {
			for _, item := range detailList {
				idDetailMap[item.UserID] = &user.BackendMemberDetailResp{
					Nickname:    item.Nickname,
					Name:        item.UserNicename,
					Url:         item.UserURL,
					DisplayName: item.DisplayName,
					Avatar:      item.Avatar,
					Gender:      int32(item.Gender),
					Birthday:    modelx.FormatNullDotTime(item.Birthday, ""),
					Country:     item.Country,
					Province:    item.Province,
					City:        item.City,
				}
			}
		}

		authFilterMap := make(map[string]map[string][]any)
		authFilterMap[model.UserAuthColumns.UserID] = map[string][]any{
			"in": uids,
		}
		authList, _, err := l.svcCtx.User.GetAuthList(l.ctx, model.M{}, -1, authFilterMap) // 读取关联表
		if err != nil {
			return nil, err
		}

		idAuthMap := make(map[uint64][]*user.UserAuth) // Map: model.User.ID => []*user.UserAuth
		if len(authList) > 0 {
			for _, item := range authList {
				var authType string
				switch item.PlatformID {
				case 1:
					authType = "微信小程序"
				default:
					authType = "其他"
				}
				idAuthMap[item.UserID] = append(idAuthMap[item.UserID], &user.UserAuth{
					Id:         int64(item.UserAuthID),
					UserId:     int64(item.UserID),
					Nickname:   item.Nickname,
					Avatar:     item.Avatar,
					Authorized: int32(item.Status),
					AuthType:   authType,
				})
			}
		}

		accountFilterMap := make(map[string]map[string][]any)
		accountFilterMap[model.UserAccountColumns.UserID] = map[string][]any{
			"in": uids,
		}
		accountList, _, err := l.svcCtx.User.GetAccountList(l.ctx, model.M{}, -1, accountFilterMap) // 读取关联表
		if err != nil {
			return nil, err
		}

		idAccountMap := make(map[uint64]*user.UserAccountResp) // Map: model.User.ID => []*user.UserAccountResp
		if len(accountList) > 0 {
			for _, item := range accountList {
				idAccountMap[item.UserID] = &user.UserAccountResp{
					HistoryPoint: int64(item.HistoryPoint),
					Balance:      int64(item.Balance),
					Level:        int32(item.Level),
				}
			}
		}

		// transFilterMap := make(map[string]map[string][]any)
		// transFilterMap[model.UserTransactionLogColumns.UserID] = map[string][]any{
		// 	"in": uids,
		// }
		// transList, _, err := l.svcCtx.User.GetTransactionLogList(l.ctx, model.M{
		// 	"orderBy": model.UserTransactionLogColumns.UserTransactionLogID + " DESC",
		// }, -1, transFilterMap) // 读取关联表
		// if err != nil {
		// 	return nil, err
		// }

		// idTransMap := make(map[uint64][]*user.Transaction) // Map: model.User.ID => []*user.Transaction
		// if len(transList) > 0 {
		// 	for _, item := range transList {
		// 		idTransMap[item.UserID] = append(idTransMap[item.UserID], &user.Transaction{
		// 			Id:           int64(item.UserTransactionLogID),
		// 			UserId:       int64(item.UserID),
		// 			UserName:     item.UserName,
		// 			AssetType:    int32(item.AssetType),
		// 			ChangeType:   int32(item.ChangeType),
		// 			ChangeAmount: int64(item.ChangeAmount),
		// 			SourceType:   int32(item.SourceType),
		// 			SourceId:     int64(item.SourceID),
		// 			SourceDesc:   item.Desc,
		// 			Status:       int32(item.Status),
		// 			CreatedAt:    modelx.FormatTime(item.CreatedAt, ""),
		// 			UpdatedAt:    modelx.FormatTime(item.UpdatedAt, ""),
		// 		})
		// 	}
		// }

		for _, item := range userList {
			detail := &user.BackendMemberDetailResp{}
			if d, ok := idDetailMap[item.ID]; ok {
				detail = d
			}
			var auths []*user.UserAuth
			if as, ok := idAuthMap[item.ID]; ok {
				auths = as[:]
			}
			account := &user.UserAccountResp{}
			if a, ok := idAccountMap[item.ID]; ok {
				account = a
			}
			// var trans []*user.Transaction
			// if ts, ok := idTransMap[item.ID]; ok {
			// 	trans = ts[:]
			// }

			var isSystem int32
			if item.IsSystem > 0 {
				isSystem = 1
			}
			members = append(members, &user.BackendMemberDetailResp{
				Id:          int64(item.ID),
				Account:     item.UserLogin,
				Mobile:      item.UserMobile,
				Email:       item.UserEmail,
				Status:      int32(item.UserStatus),
				DelStatus:   int32(item.DelStatus),
				IsSystem:    isSystem,
				Nickname:    detail.Nickname,
				Name:        detail.Name,
				Url:         detail.Url,
				DisplayName: detail.DisplayName,
				Avatar:      detail.Avatar,
				Gender:      detail.Gender,
				Birthday:    detail.Birthday,
				Country:     detail.Country,
				Province:    detail.Province,
				City:        detail.City,
				Gems:        account.Balance,
				Integral:    account.HistoryPoint,
				Level:       account.Level,
				UserAuth:    auths,
				// Trans:       trans,
			})
		}
	}

	return &user.BackendMemberListResp{
		Total: count,
		List:  members,
	}, nil
}
